package com.action;

import com.annotation.Lock;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bean.ResponseBean;
import com.pojo.Admin;
import com.pojo.Chongzhi;
import com.pojo.Staff;
import com.service.ChongzhiService;
import com.service.StaffService;
import com.util.StringUtil;
import com.util.ValidateHelper;
import com.vo.ChongzhiVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

@CrossOrigin
@RestController
@RequestMapping("/cz")
public class ChongzhiAction {

    @Autowired
    private ChongzhiService czService;
    @Autowired
    private StaffService staffService;

    @Value("${upload.dir}")
    private String download ;

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate ;

    /**
     * 获取UUID
     */
    @RequestMapping("/getUUid")
    public ResponseBean getUUid() {
        String random1 = UUID.randomUUID().toString();
        String random2 = UUID.randomUUID().toString();
        String random3 = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set("cz" + random1,random1,2 * 60, TimeUnit.SECONDS);
        redisTemplate.opsForValue().set("czPre" + random2,random2,2 * 60, TimeUnit.SECONDS);
        redisTemplate.opsForValue().set("saveCz" + random3,random3,2 * 60, TimeUnit.SECONDS);
        Map result = new HashMap();
        result.put("cz",random1);
        result.put("czPre",random2);
        result.put("saveCz",random3);
        return new ResponseBean(1,1,"生成随机数成功",result);
    }

    /**
     * 根据卡号获取用户信息
     */
    @RequestMapping("/getStaffInfo")
    public ResponseBean getStaffInfo(String cardNo, HttpServletRequest request) {
        String queryStr = null;
        Map<String,Object> resultMap = staffService.getStaffInfoByCz(cardNo, queryStr);
        if (ValidateHelper.isEmptyMap(resultMap)) {
            return new ResponseBean(0,1,"会员不存在","该卡没有绑定会员");
        }
        return new ResponseBean(1,1,"读取成功",resultMap);
    }

    /**
     * 充值
     * @param cz
     * @return
     */
    @RequestMapping("/saveCz")
    @ResponseBody
    @Lock(name = "cz_pre")
    public ResponseBean saveCz(@RequestBody Chongzhi cz, String czUUID, HttpServletRequest request) {
        Admin admin = (Admin) request.getSession().getAttribute("admin");
//        if (!czUUID.equals(redisTemplate.opsForValue().get("saveCz" + czUUID))) {
//            return new ResponseBean(600,1,"请勿重复提交！");
//        }else {
//            redisTemplate.opsForValue().set("saveCz" + czUUID, null);
//        }
        Chongzhi saveCz = new Chongzhi();
        saveCz.setCardNo(cz.getCardNo());
        saveCz.setPin(cz.getPin());
        BigDecimal czAmount = cz.getCzAmount();
        BigDecimal balance = cz.getStaffBalance();
        saveCz.setCzAmount(czAmount);
        saveCz.setStaffBalance(czAmount.add(balance));
        saveCz.setStaffId(cz.getStaffId());
        saveCz.setCzTime(new Date());
        if (null != admin) {
            saveCz.setOperUser(admin.getId());
        }
        int c = czService.saveCz(saveCz);
        Staff staff = new Staff();
        staff.setId(cz.getStaffId());
        staff.setCardBalance(czAmount.add(balance));
        boolean updFlag = staffService.updateById(staff);
        if (c != 1 && !updFlag) {
            return new ResponseBean(0,1, "充值失败");
        }
//        redisTemplate.opsForValue().set("submitFlag", null);
        return new ResponseBean(1,1, "充值成功");
    }
    /**
     * 获取用户充值记录
     */
    @RequestMapping("/getCzByUser")
    public ResponseBean getCzByUser(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit, String staffId, @RequestParam(required = false) String start_time, @RequestParam(required = false) String end_time) {
        if(StringUtil.isNull(start_time)){
            start_time=null;
        }
        if(StringUtil.isNull(end_time)){
            end_time=null;
        }
        IPage<ChongzhiVo> czList = czService.getCzRecordByUser(page,limit,staffId,start_time,end_time);
        return new ResponseBean(0, czList.getTotal(), "成功", czList.getRecords());
    }

    /**
     * 获取充值记录
     */
    @RequestMapping("/getCzRecord")
    public ResponseBean getCzRecord(String staffName, int page, int limit, @RequestParam(required = false) String start_time, @RequestParam(required = false) String end_time,
                                    HttpServletRequest request) {
        String queryStr = null;
        if(StringUtil.isNull(start_time)){
            start_time=null;
        }
        if(StringUtil.isNull(end_time)){
            end_time=null;
        }
        if(StringUtil.isNull(staffName)){
            staffName=null;
        }
        IPage iPage = czService.getCzRecord(page,limit,staffName,start_time,end_time, queryStr);
        return new ResponseBean(0, iPage.getTotal(), "成功", iPage.getRecords());
    }

    /**
     * 导出Excel
     */
    @RequestMapping("/exportExcelByCz")
    public ResponseEntity<InputStreamResource> exportExcelByCz(String staffName, String start_time, String end_time, HttpServletRequest request) throws IOException {
        String queryStr = null;
        if(StringUtil.isNull(start_time)){
            start_time=null;
        }
        if(StringUtil.isNull(end_time)){
            end_time=null;
        }
        if(StringUtil.isNull(staffName)){
            staffName=null;
        }
        List<ChongzhiVo> czList = czService.exportByExecl(staffName,start_time,end_time, queryStr);
        String cnFileName = new String("充值记录".getBytes(), "utf-8");
        String name = cnFileName + new Date().getTime() + ".xls" ;
        String fileName = download + "/excel/" + name ;
        if(!new File(download + "/excel/").exists()) {
            new File(download + "/excel/").mkdirs() ;
        }
        try {
//            ExcelUtil.exportExcelByCz(fileName,"充值记录",czList,"cz");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        FileSystemResource file = new FileSystemResource (fileName) ;
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", new String(name.getBytes(), "iso-8859-1")));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }
}
